document.addEventListener('DOMContentLoaded', () => {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        const tabId = tabs[0].id;

        // 确保内容脚本已注入
        chrome.scripting.executeScript({
            target: { tabId: tabId },
            files: ['content_script.js']
        }, () => {
            chrome.tabs.sendMessage(tabId, { action: "extractSSHInfo" }, (response) => {
                if (response) {
                    const { command, password, isRDP } = response;

                    const container = document.querySelector('.container');
                    container.innerHTML = ''; // 清空容器

                    // 根据是 RDP 还是 SSH 动态生成格子
                    if (isRDP) {
                        const rdpCommandBlock = createBlock(command, 'rdpCommand');
                        container.appendChild(rdpCommandBlock);
                    } else {
                        const sshCommandBlock = createBlock(command, 'connectionCommand');
                        const passwordBlock = createBlock(password, 'password');
                        container.appendChild(sshCommandBlock);
                        container.appendChild(passwordBlock);
                    }
                }
            });
        });
    });

    function createBlock(content, id) {
        const block = document.createElement('div');
        block.className = 'block';
        block.id = id;
        block.textContent = content;
        block.addEventListener('click', () => copyToClipboard(id));
        return block;
    }

    function copyToClipboard(elementId) {
        const element = document.getElementById(elementId);
        const text = element.textContent;

        const textarea = document.createElement('textarea');
        textarea.value = text;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
    }
});
